{% extends 'base.html' %}
{% load static %}

{% block title %}资产详情 - 固定资产管理系统{% endblock %}

{% block content %}
<div class="row">
    <div class="col-md-12">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="{% url 'assets:index' %}">首页</a></li>
                <li class="breadcrumb-item"><a href="{% url 'assets:asset_list' %}">资产管理</a></li>
                <li class="breadcrumb-item active" aria-current="page">资产详情</li>
            </ol>
        </nav>
        
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h2 class="mb-0 d-flex align-items-center gap-2">
                <i class="fas fa-cube me-2"></i>
                <span>{{ asset.name }}</span>
                {% if asset.ledger and asset.ledger.organization %}
                <span class="badge bg-secondary text-light" title="所属组织">
                    <i class="fas fa-building me-1"></i>{{ asset.ledger.organization.name }}
                </span>
                {% endif %}
                {% if asset.asset_number %}
                <span class="badge bg-light text-dark border" title="资产编号">
                    <i class="fas fa-hashtag me-1"></i><code class="m-0 p-0" style="background:none;border:none;">{{ asset.asset_number }}</code>
                </span>
                {% endif %}
            </h2>
            <div class="btn-group">
                <a href="{% url 'assets:asset_update' asset.pk %}" class="btn btn-primary">
                    <i class="fas fa-edit me-1"></i>编辑资产
                </a>
                <button type="button" class="btn btn-outline-primary dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown">
                    <span class="visually-hidden">更多操作</span>
                </button>
                <ul class="dropdown-menu">
                    <li><a class="dropdown-item" href="{% url 'assets:asset_qr_code_view' asset.pk %}">
                        <i class="fas fa-qrcode me-2"></i>查看二维码
                    </a></li>
                    <li><a class="dropdown-item" href="{% url 'assets:asset_print_label' asset.pk %}">
                        <i class="fas fa-print me-2"></i>打印标签
                    </a></li>
                    <li><hr class="dropdown-divider"></li>
                    <li><a class="dropdown-item" href="{% url 'assets:asset_list' %}">
                        <i class="fas fa-arrow-left me-2"></i>返回列表
                    </a></li>
                </ul>
            </div>
        </div>
        
        <div class="row">
            <div class="col-md-8">
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0">
                            <i class="fas fa-info-circle me-2"></i>基本信息
                        </h5>
                    </div>
                    <div class="card-body">
                        <style>
                          .basic-info-table td:first-child { width: 30%; white-space: nowrap; }
                        </style>
                        <div class="row">
                            <div class="col-lg-4 col-md-6">
                                <table class="table table-borderless table-sm basic-info-table mb-0">
                                    <tr>
                                        <td class="text-muted">所属组织:</td>
                                        <td>
                                            {% if asset.ledger and asset.ledger.organization %}
                                                <i class="fas fa-building me-1 text-secondary"></i>{{ asset.ledger.organization.name }}
                                            {% else %}
                                                <span class="text-muted">-</span>
                                            {% endif %}
                                        </td>
                                    </tr>
                                    <tr>
                                        <td class="text-muted">资产编号:</td>
                                        <td><code>{{ asset.asset_number }}</code></td>
                                    </tr>
                                    <tr>
                                        <td class="text-muted">资产名称:</td>
                                        <td><strong>{{ asset.name }}</strong></td>
                                    </tr>
                                    <tr>
                                        <td class="text-muted">资产类别:</td>
                                        <td>
                                            {% if asset.category %}
                                                <span class="badge bg-info">{{ asset.category.name }}</span>
                                            {% else %}
                                                <span class="text-muted">-</span>
                                            {% endif %}
                                        </td>
                                    </tr>
                                    <tr>
                                        <td class="text-muted">启用日期:</td>
                                        <td><i class="fas fa-calendar me-1 text-muted"></i>{{ asset.purchase_date|date:"Y-m-d" }}</td>
                                    </tr>
                                </table>
                            </div>
                            <div class="col-lg-4 col-md-6">
                                <table class="table table-borderless table-sm basic-info-table mb-0">
                                    <tr>
                                        <td class="text-muted">资产状态:</td>
                                        <td>
                                            {% if asset.status == 'idle' %}
                                                <span class="badge bg-secondary"><i class="fas fa-pause me-1"></i>闲置</span>
                                            {% elif asset.status == 'in_use' %}
                                                <span class="badge bg-success"><i class="fas fa-play me-1"></i>在用</span>
                                            {% elif asset.status == 'maintenance' %}
                                                <span class="badge bg-warning"><i class="fas fa-tools me-1"></i>维修中</span>
                                            {% elif asset.status == 'scrapped' %}
                                                <span class="badge bg-danger"><i class="fas fa-trash me-1"></i>已报废</span>
                                            {% elif asset.status == 'borrowed' %}
                                                <span class="badge bg-info"><i class="fas fa-handshake me-1"></i>借出</span>
                                            {% else %}
                                                <span class="badge bg-light text-dark">{{ asset.get_status_display }}</span>
                                            {% endif %}
                                        </td>
                                    </tr>
                                    <tr>
                                        <td class="text-muted">所属部门:</td>
                                        <td>
                                            {% if asset.department %}
                                                <i class="fas fa-building me-1 text-primary"></i>{{ asset.department.name }}
                                            {% else %}
                                                <span class="text-muted">-</span>
                                            {% endif %}
                                        </td>
                                    </tr>
                                    <tr>
                                        <td class="text-muted">使用人:</td>
                                        <td>
                                            {% if asset.user %}
                                                <i class="fas fa-user me-1 text-info"></i>{{ asset.user.get_full_name|default:asset.user.username }}
                                            {% else %}
                                                <span class="text-muted">-</span>
                                            {% endif %}
                                        </td>
                                    </tr>
                                    <tr>
                                        <td class="text-muted">位置:</td>
                                        <td>
                                            {% if asset.location %}
                                                <i class="fas fa-map-marker-alt me-1 text-success"></i>{{ asset.location.name }}
                                            {% else %}
                                                <span class="text-muted">-</span>
                                            {% endif %}
                                        </td>
                                    </tr>
                                </table>
                            </div>
                            <div class="col-lg-4 col-md-12">
                                <table class="table table-borderless table-sm basic-info-table mb-0">
                                    <tr>
                                        <td class="text-muted">采购价格:</td>
                                        <td><i class="fas fa-yen-sign me-1 text-success"></i>{{ asset.purchase_price|floatformat:2 }}</td>
                                    </tr>
                                    <tr>
                                        <td class="text-muted">保修期:</td>
                                        <td>
                                            {% if asset.warranty_period %}
                                                <i class="fas fa-shield-alt me-1 text-warning"></i>{{ asset.warranty_period }} 个月
                                            {% else %}
                                                <span class="text-muted">-</span>
                                            {% endif %}
                                        </td>
                                    </tr>
                                    <tr>
                                        <td class="text-muted">折旧率:</td>
                                        <td>
                                            {% if asset.depreciation_rate %}
                                                <i class="fas fa-chart-line me-1 text-info"></i>{{ asset.depreciation_rate }}%
                                            {% else %}
                                                <span class="text-muted">-</span>
                                            {% endif %}
                                        </td>
                                    </tr>
                                    <tr>
                                        <td class="text-muted">创建时间:</td>
                                        <td><i class="fas fa-clock me-1 text-muted"></i>{{ asset.created_at|date:"Y-m-d H:i" }}</td>
                                    </tr>
                                </table>
                            </div>
                        </div>
                        
                        {% if asset.description %}
                        <div class="mt-3">
                            <h6 class="text-muted">描述:</h6>
                            <p class="mb-0">{{ asset.description }}</p>
                        </div>
                        {% endif %}
                    </div>
                </div>
                
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0">
                            <i class="fas fa-handshake me-2"></i>供应商与合同信息
                        </h5>
                    </div>
                    <div class="card-body">
                        <table class="table table-borderless">
                            <tr>
                                <td width="30%" class="text-muted">供应商:</td>
                                <td>
                                    {% if asset.supplier %}
                                        <i class="fas fa-truck me-1 text-info"></i>{{ asset.supplier.name }}
                                        {% if asset.supplier.contact_person %}
                                            <br><small class="text-muted">联系人: {{ asset.supplier.contact_person }}</small>
                                        {% endif %}
                                        {% if asset.supplier.phone %}
                                            <br><small class="text-muted">电话: {{ asset.supplier.phone }}</small>
                                        {% endif %}
                                    {% else %}
                                        <span class="text-muted">-</span>
                                    {% endif %}
                                </td>
                            </tr>
                            <tr>
                                <td class="text-muted">合同:</td>
                                <td>
                                    {% if asset.contract %}
                                        <i class="fas fa-file-contract me-1 text-primary"></i>{{ asset.contract.name }}
                                        {% if asset.contract.contract_number %}
                                            <br><small class="text-muted">合同号: {{ asset.contract.contract_number }}</small>
                                        {% endif %}
                                        {% if asset.contract.start_date and asset.contract.end_date %}
                                            <br><small class="text-muted">
                                                有效期: {{ asset.contract.start_date|date:"Y-m-d" }} 至 {{ asset.contract.end_date|date:"Y-m-d" }}
                                            </small>
                                        {% endif %}
                                    {% else %}
                                        <span class="text-muted">-</span>
                                    {% endif %}
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>
            
            <div class="col-md-4">
                <!-- 资产状态卡片 -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0">
                            <i class="fas fa-chart-pie me-2"></i>资产状态
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="mb-2">
                            {% if asset.status == 'scrapped' %}
                                <span class="badge bg-danger"><i class="fas fa-trash me-1"></i>已报废</span>
                            {% elif asset.status == 'maintenance' %}
                                <span class="badge bg-warning text-dark"><i class="fas fa-tools me-1"></i>维修中</span>
                            {% elif asset.status == 'in_use' %}
                                <span class="badge bg-success"><i class="fas fa-play me-1"></i>使用中</span>
                            {% elif asset.status == 'idle' %}
                                <span class="badge bg-secondary"><i class="fas fa-pause me-1"></i>闲置</span>
                            {% elif asset.status == 'borrowed' %}
                                <span class="badge bg-info text-dark"><i class="fas fa-handshake me-1"></i>借出</span>
                            {% else %}
                                <span class="badge bg-light text-dark">{{ asset.get_status_display }}</span>
                            {% endif %}
                        </div>

                        <div class="row text-center g-2">
                            <div class="col-6">
                                <h5 class="text-primary mb-0">{{ asset.purchase_price|floatformat:0 }}</h5>
                                <small class="text-muted">采购价格(元)</small>
                            </div>
                            <div class="col-6">
                                <h5 class="text-info mb-0">{{ asset.warranty_period|default:0 }}</h5>
                                <small class="text-muted">保修期(月)</small>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 快速操作 -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0">
                            <i class="fas fa-bolt me-2"></i>快速操作
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="d-grid gap-2">
                            {% if asset.status != 'scrapped' %}
                                <a href="{% url 'assets:asset_allocate' asset.pk %}" class="btn btn-success btn-sm">
                                    <i class="fas fa-user-check me-2"></i>分配资产
                                </a>
                                <a href="{% url 'assets:asset_transfer' asset.pk %}" class="btn btn-info btn-sm">
                                    <i class="fas fa-exchange-alt me-2"></i>转移资产
                                </a>
                                <button type="button" class="btn btn-outline-success btn-sm" data-asset-id="{{ asset.pk }}" data-asset-name="{{ asset.name|escapejs }}" onclick="recycleAssetDetail(this.dataset.assetId, this.dataset.assetName)">
                                    <i class="fas fa-recycle me-2"></i>回收资产
                                </button>
                                <a href="{% url 'assets:asset_maintenance' asset.pk %}" class="btn btn-warning btn-sm">
                                    <i class="fas fa-tools me-2"></i>维护资产
                                </a>
                                <a href="{% url 'assets:asset_scrap' asset.pk %}" class="btn btn-danger btn-sm">
                                    <i class="fas fa-trash me-2"></i>报废资产
                                </a>
                            {% else %}
                                <div class="text-muted text-center">
                                    <i class="fas fa-ban fa-2x mb-2"></i>
                                    <p class="mb-0">资产已报废，无法操作</p>
                                </div>
                            {% endif %}
                        </div>
                    </div>
                </div>
                
                <!-- 统计信息 -->
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">
                            <i class="fas fa-chart-bar me-2"></i>统计信息
                        </h5>
                    </div>
                    <div class="card-body">
                        <table class="table table-borderless table-sm">
                            <tr>
                                <td class="text-muted">创建时间:</td>
                                <td>
                                    <i class="fas fa-calendar me-1 text-muted"></i>
                                    {{ asset.created_at|date:"Y-m-d H:i" }}
                                </td>
                            </tr>
                            <tr>
                                <td class="text-muted">最后更新:</td>
                                <td>
                                    <i class="fas fa-clock me-1 text-muted"></i>
                                    {{ asset.updated_at|date:"Y-m-d H:i" }}
                                </td>
                            </tr>
                            <tr>
                                <td class="text-muted">操作日志:</td>
                                <td>
                                    <i class="fas fa-history me-1 text-muted"></i>
                                    {{ logs_count }} 条记录
                                </td>
                            </tr>
                            {% if asset.images.count > 0 %}
                            <tr>
                                <td class="text-muted">资产图片:</td>
                                <td>
                                    <i class="fas fa-images me-1 text-muted"></i>
                                    {{ asset.images.count }} 张图片
                                </td>
                            </tr>
                            {% endif %}
                        </table>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 增强的操作日志显示 -->
        <div class="card">
            <div class="card-header">
                <div class="d-flex flex-wrap align-items-end gap-2">
                    <h5 class="mb-0 me-2 d-flex align-items-center gap-2">
                        <i class="fas fa-history me-2"></i>操作日志
                        <span class="badge bg-light text-dark border" id="assetLogsCountBadge">共 {{ logs_count|default:0 }} 条</span>
                    </h5>
                    <div id="assetLogsAria" class="visually-hidden" aria-live="polite"></div>
                    <form id="assetLogsFilterForm" class="row g-2 align-items-end flex-grow-1">
                        <div class="col-md-2 col-sm-6">
                            <label class="form-label form-label-sm mb-1">操作类型</label>
                            <select name="action" class="form-select form-select-sm">
                                <option value="">全部</option>
                                <option value="create" {% if filters.action == 'create' %}selected{% endif %}>创建</option>
                                <option value="update" {% if filters.action == 'update' %}selected{% endif %}>更新</option>
                                <option value="allocate" {% if filters.action == 'allocate' %}selected{% endif %}>分配</option>
                                <option value="transfer" {% if filters.action == 'transfer' %}selected{% endif %}>转移</option>
                                <option value="maintenance" {% if filters.action == 'maintenance' %}selected{% endif %}>维修</option>
                                <option value="scrap" {% if filters.action == 'scrap' %}selected{% endif %}>报废</option>
                                <option value="borrow" {% if filters.action == 'borrow' %}selected{% endif %}>借用</option>
                                <option value="return" {% if filters.action == 'return' %}selected{% endif %}>归还</option>
                                <option value="image_upload" {% if filters.action == 'image_upload' %}selected{% endif %}>图片上传</option>
                                <option value="image_delete" {% if filters.action == 'image_delete' %}selected{% endif %}>图片删除</option>
                                <option value="inventory" {% if filters.action == 'inventory' %}selected{% endif %}>盘点</option>
                                <option value="qr_generate" {% if filters.action == 'qr_generate' %}selected{% endif %}>二维码生成</option>
                                <option value="label_print" {% if filters.action == 'label_print' %}selected{% endif %}>标签打印</option>
                                <option value="status_change" {% if filters.action == 'status_change' %}selected{% endif %}>状态变更</option>
                                <option value="location_change" {% if filters.action == 'location_change' %}selected{% endif %}>位置变更</option>
                                <option value="user_change" {% if filters.action == 'user_change' %}selected{% endif %}>使用人变更</option>
                                <option value="department_change" {% if filters.action == 'department_change' %}selected{% endif %}>部门变更</option>
                            </select>
                        </div>
                        <div class="col-md-2 col-sm-6">
                            <label class="form-label form-label-sm mb-1">操作人</label>
                            <select name="operator" class="form-select form-select-sm">
                                <option value="">全部</option>
                                {% for u in operators %}
                                <option value="{{ u.id }}" {% if filters.operator|default:'' == u.id|stringformat:'s' %}selected{% endif %}>
                                    {{ u.get_full_name|default:u.username }}
                                </option>
                                {% endfor %}
                            </select>
                        </div>
                        <div class="col-md-2 col-sm-6">
                            <label class="form-label form-label-sm mb-1">开始日期</label>
                            <input type="date" name="date_from" value="{{ filters.date_from|default:'' }}" class="form-control form-control-sm" />
                        </div>
                        <div class="col-md-2 col-sm-6">
                            <label class="form-label form-label-sm mb-1">结束日期</label>
                            <input type="date" name="date_to" value="{{ filters.date_to|default:'' }}" class="form-control form-control-sm" />
                        </div>
                        <div class="col-md-3 col-12">
                            <label class="form-label form-label-sm mb-1">快速选择</label>
                            <div class="d-flex flex-wrap gap-1">
                                <button class="btn btn-outline-secondary btn-xs btn-sm" type="button" data-preset="last7">最近7天</button>
                                <button class="btn btn-outline-secondary btn-xs btn-sm" type="button" data-preset="last30">最近30天</button>
                                <button class="btn btn-outline-secondary btn-xs btn-sm" type="button" data-preset="thisWeek">本周</button>
                                <button class="btn btn-outline-secondary btn-xs btn-sm" type="button" data-preset="thisMonth">本月</button>
                                <button class="btn btn-outline-secondary btn-xs btn-sm" type="button" data-preset="all">全部</button>
                            </div>
                        </div>
                        <div class="col-md-2 col-sm-6">
                            <label class="form-label form-label-sm mb-1">关键词</label>
                            <input type="text" name="keyword" value="{{ filters.keyword|default:'' }}" placeholder="描述包含..." class="form-control form-control-sm" />
                        </div>
                        <div class="col-md-1 col-sm-6">
                            <label class="form-label form-label-sm mb-1">每页</label>
                            <select name="per_page" class="form-select form-select-sm">
                                <option value="10" {% if per_page == 10 %}selected{% endif %}>10</option>
                                <option value="20" {% if per_page == 20 %}selected{% endif %}>20</option>
                                <option value="50" {% if per_page == 50 %}selected{% endif %}>50</option>
                                <option value="100" {% if per_page == 100 %}selected{% endif %}>100</option>
                            </select>
                        </div>
                        <div class="col-md-1 d-grid">
                            <button class="btn btn-primary btn-sm" type="submit"><i class="fas fa-search me-1"></i>查询</button>
                        </div>
                        <div class="col-md-1 d-grid">
                            <button class="btn btn-outline-secondary btn-sm" type="button" id="btnResetLogsFilter">重置</button>
                        </div>
                        <div class="col-md-1 d-grid">
                            <button class="btn btn-outline-success btn-sm" type="button" id="btnExportLogs"><i class="fas fa-file-export me-1"></i>导出</button>
                        </div>
                    </form>
                </div>
            </div>
            <div class="card-body">
                <div id="assetLogsLoading" class="d-none text-center py-3">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">加载中...</span>
                    </div>
                </div>
                <div id="assetLogsContainer">
                    {% include 'assets/partials/asset_logs_table.html' %}
                </div>
            </div>
        </div>

        <script>
        (function(){
            const form = document.getElementById('assetLogsFilterForm');
            const container = document.getElementById('assetLogsContainer');
            const loading = document.getElementById('assetLogsLoading');
            const resetBtn = document.getElementById('btnResetLogsFilter');
            const exportBtn = document.getElementById('btnExportLogs');
            const ariaLive = document.getElementById('assetLogsAria');

            function buildQuery(params){
                const usp = new URLSearchParams(params);
                usp.set('fragment', 'logs');
                return '?' + usp.toString();
            }

            function getFormParams(){
                const fd = new FormData(form);
                const params = {};
                for (const [k,v] of fd.entries()){
                    if (v !== '') params[k] = v;
                }
                params['page'] = 1; // reset to first page on filter
                return params;
            }

            function setLoadingState(disabled){
                if (!form) return;
                form.querySelectorAll('input,select,button').forEach(el => el.disabled = !!disabled);
            }

            function smoothFocus(){
                const card = container.closest('.card');
                if (card && 'scrollIntoView' in card) {
                    card.scrollIntoView({ behavior: 'smooth', block: 'start' });
                }
            }

            function updatePresetsActive(){
                const df = form.querySelector('input[name="date_from"]').value;
                const dt = form.querySelector('input[name="date_to"]').value;
                const now = new Date();
                const fmt = d => `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;
                const monday = (() => { const d = new Date(now); const day = d.getDay(); const diff = (day===0? -6:1)-day; d.setDate(d.getDate()+diff); return d; })();
                const monthStart = new Date(now.getFullYear(), now.getMonth(), 1);
                const monthEnd = new Date(now.getFullYear(), now.getMonth()+1, 0);
                const match = (a,b) => a && b && a===b;
                const setActive = key => {
                    form.querySelectorAll('button[data-preset]').forEach(b=>b.classList.remove('active'));
                    const btn = form.querySelector(`button[data-preset="${key}"]`);
                    btn && btn.classList.add('active');
                };
                if (match(df, fmt(new Date(now.getFullYear(), now.getMonth(), now.getDate()-6))) && match(dt, fmt(now))) return setActive('last7');
                if (match(df, fmt(new Date(now.getFullYear(), now.getMonth(), now.getDate()-29))) && match(dt, fmt(now))) return setActive('last30');
                if (match(df, fmt(monday)) && match(dt, fmt(now))) return setActive('thisWeek');
                if (match(df, fmt(monthStart)) && match(dt, fmt(monthEnd))) return setActive('thisMonth');
                if (!df && !dt) return setActive('all');
                form.querySelectorAll('button[data-preset]').forEach(b=>b.classList.remove('active'));
            }

            async function loadLogs(params){
                const query = buildQuery(params);
                const url = window.location.pathname + query;
                try {
                    loading && loading.classList.remove('d-none');
                    setLoadingState(true);
                    const resp = await fetch(url, { headers: { 'X-Requested-With': 'XMLHttpRequest' } });
                    const html = await resp.text();
                    container.innerHTML = html;
                    // 更新地址栏（移除 fragment 参数）
                    const usp = new URLSearchParams(params);
                    usp.delete('fragment');
                    history.replaceState(null, '', window.location.pathname + (usp.toString() ? ('?' + usp.toString()) : ''));
                    // 更新计数徽章
                    const meta = container.querySelector('#assetLogsMeta');
                    const badge = document.getElementById('assetLogsCountBadge');
                    if (meta && badge) {
                        const cnt = meta.dataset.count || '0';
                        badge.textContent = `共 ${cnt} 条`;
                        if (ariaLive) ariaLive.textContent = `已加载 ${cnt} 条记录`;
                    }
                    updatePresetsActive();
                    smoothFocus();
                } catch (e) {
                    console && console.error && console.error('加载日志失败', e);
                } finally {
                    loading && loading.classList.add('d-none');
                    setLoadingState(false);
                }
            }

            // 根据 URL 同步表单值
            function syncFormFromURL(){
                const usp = new URLSearchParams(location.search);
                const setVal = (name, val) => {
                    const el = form.querySelector(`[name="${name}"]`);
                    if (el !== null) el.value = val || '';
                };
                ['action','operator','date_from','date_to','keyword','per_page'].forEach(k => setVal(k, usp.get(k)));
            }

            form && form.addEventListener('submit', function(e){
                e.preventDefault();
                const params = getFormParams();
                loadLogs(params);
            });

            resetBtn && resetBtn.addEventListener('click', function(){
                form.reset();
                loadLogs({ fragment: 'logs' });
            });

            // 事件代理：分页点击
            container && container.addEventListener('click', function(e){
                const a = e.target.closest('a.page-link');
                if (!a) return;
                const href = a.getAttribute('href') || '';
                if (!href.startsWith('?')) return; // let normal links pass
                e.preventDefault();
                // 使用当前 URL 的查询参数作为基础，保持筛选不丢失
                const current = Object.fromEntries(new URLSearchParams(location.search).entries());
                // parse page from href
                const usp = new URLSearchParams(href.substring(1));
                const page = usp.get('page') || 1;
                current['page'] = page;
                current['fragment'] = 'logs';
                loadLogs(current);
            });

            // 自动提交：下拉/日期更改即加载
            const autoChangeSelectors = ['select[name="action"]','select[name="operator"]','select[name="per_page"]','input[name="date_from"]','input[name="date_to"]'];
            autoChangeSelectors.forEach(sel => {
                const el = form.querySelector(sel);
                el && el.addEventListener('change', () => {
                    const params = getFormParams();
                    loadLogs(params);
                });
            });

            // 关键词输入防抖
            const kw = form.querySelector('input[name="keyword"]');
            let kwTimer = null;
            kw && kw.addEventListener('input', function(){
                clearTimeout(kwTimer);
                kwTimer = setTimeout(() => {
                    const params = getFormParams();
                    loadLogs(params);
                }, 400);
            });

            // 处理浏览器前进/后退
            window.addEventListener('popstate', function(){
                syncFormFromURL();
                const current = Object.fromEntries(new URLSearchParams(location.search).entries());
                current['fragment'] = 'logs';
                loadLogs(current);
            });

            // 初始同步一次（若直接带查询进入页面）
            syncFormFromURL();
            updatePresetsActive();

            // 快速日期预设
            function fmt(d){
                const y = d.getFullYear();
                const m = String(d.getMonth()+1).padStart(2,'0');
                const day = String(d.getDate()).padStart(2,'0');
                return `${y}-${m}-${day}`;
            }
            function getMonday(d){
                const day = d.getDay();
                const diff = (day === 0 ? -6 : 1) - day; // Monday as 1
                const nd = new Date(d);
                nd.setDate(d.getDate() + diff);
                return nd;
            }
            function monthRange(d){
                const start = new Date(d.getFullYear(), d.getMonth(), 1);
                const end = new Date(d.getFullYear(), d.getMonth()+1, 0);
                return [start, end];
            }
            const presetsWrap = form.querySelector('[data-preset]')?.parentElement;
            form.querySelectorAll('button[data-preset]').forEach(btn => {
                btn.addEventListener('click', () => {
                    const now = new Date();
                    const df = form.querySelector('input[name="date_from"]');
                    const dt = form.querySelector('input[name="date_to"]');
                    const type = btn.getAttribute('data-preset');
                    if (type === 'last7'){
                        const start = new Date(now);
                        start.setDate(now.getDate() - 6);
                        df.value = fmt(start);
                        dt.value = fmt(now);
                    } else if (type === 'last30'){
                        const start = new Date(now);
                        start.setDate(now.getDate() - 29);
                        df.value = fmt(start);
                        dt.value = fmt(now);
                    } else if (type === 'thisWeek'){
                        const start = getMonday(now);
                        df.value = fmt(start);
                        dt.value = fmt(now);
                    } else if (type === 'thisMonth'){
                        const [start, end] = monthRange(now);
                        df.value = fmt(start);
                        dt.value = fmt(end);
                    } else if (type === 'all'){
                        df.value = '';
                        dt.value = '';
                    }
                    form.querySelectorAll('button[data-preset]').forEach(b=>b.classList.remove('active'));
                    btn.classList.add('active');
                    const params = getFormParams();
                    loadLogs(params);
                });
            });

            // 导出 CSV
            exportBtn && exportBtn.addEventListener('click', function(){
                const usp = new URLSearchParams(new FormData(form));
                // 移除空值
                Array.from(usp.keys()).forEach(k => { if (!usp.get(k)) usp.delete(k); });
                usp.set('export', 'csv');
                const url = window.location.pathname + '?' + usp.toString();
                window.location.href = url;
            });
        })();
        </script>
        
        <!-- 图片管理区域 -->
        <div class="row">
            <div class="col-12">
                {% include 'assets/asset_image_manager.html' %}
            </div>
        </div>
    </div>
</div>

<!-- 图片查看模态框 -->
<div class="modal fade" id="imageModal" tabindex="-1" aria-labelledby="imageModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="imageModalLabel">资产图片</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body text-center">
                <img id="modalImage" src="" alt="" style="max-width: 100%; max-height: 70vh; object-fit: contain;">
            </div>
        </div>
    </div>
</div>

{% endblock %}

{% block extra_js %}
<script src="{% static 'js/asset_detail.js' %}"></script>
<script>
// Ensure asset_detail.js can read the asset id from document.body
document.addEventListener('DOMContentLoaded', function(){
    try { document.body.setAttribute('data-asset-id', '{{ asset.pk }}'); } catch (e) {}
});
function recycleAssetDetail(assetId, assetName) {
    if (confirm(`确定要回收资产 "${assetName}" 吗？\n\n回收后：\n- 使用人将被清空\n- 部门将设置为信息技术部\n- 状态将设置为闲置`)) {
        // 创建表单提交回收请求
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = '{% url "assets:asset_recycle" 0 %}'.replace('0', assetId);
        
        // 添加CSRF token
        const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value;
        const csrfInput = document.createElement('input');
        csrfInput.type = 'hidden';
        csrfInput.name = 'csrfmiddlewaretoken';
        csrfInput.value = csrfToken;
        form.appendChild(csrfInput);
        
        // 提交表单
        document.body.appendChild(form);
        form.submit();
    }
}
</script>
{% endblock %}